package com.itheima.app.manager;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.Notification;
import com.itheima.domain.db.Question;
import com.itheima.domain.db.User;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.vo.ErrorResult;
import com.itheima.domain.vo.PageBeanVo;
import com.itheima.domain.vo.SettingVo;
import com.itheima.service.db.BlackListService;
import com.itheima.service.db.NotificationService;
import com.itheima.service.db.QuestionService;
import com.itheima.service.db.UserService;
import com.itheima.util.ConstantUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

@Service //spring
public class SettingManager {

    @Reference //dubbo
    QuestionService questionService;

    @Reference
    NotificationService notificationService;

    @Reference
    BlackListService blackListService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Reference
    UserService userService;

    public ResponseEntity findSetting() {
        //1.获取用户id
        Long userId = UserHolder.get().getId();

        //2.调用questionService查询问题
        Question question = questionService.findByUserId(userId);

        //3.调用notificationService查询 通知设置
        Notification notification = notificationService.findByUserId(userId);

        //4.创建SettingVo
        SettingVo settingVo = new SettingVo();

        //5.给vo设置问题
        if (question != null) {
            settingVo.setStrangerQuestion(question.getStrangerQuestion());
        }

        //6.给vo设置 用户设置
        if (notification != null) {
            settingVo.setPinglunNotification(notification.getPinglunNotification());
            settingVo.setLikeNotification(notification.getLikeNotification());
            settingVo.setGonggaoNotification(notification.getGonggaoNotification());
        }

        //7. 给vo设置用户id
        settingVo.setId(userId);
        return ResponseEntity.ok(settingVo);
    }

    public ResponseEntity setQuestion(String content) {
        //1.获取用户id
        Long userId = UserHolder.get().getId();

        //2.通过用户id查询陌生人问题
        Question question = questionService.findByUserId(userId);

        //3.判断问题对象是否为null
        if (question == null) {
            //3.1若为null,添加
            question = new Question();
            question.setUserId(userId);
            question.setStrangerQuestion(content);

            questionService.save(question);
        }else {
            //3.2若不为null,修改
            question.setStrangerQuestion(content);

            questionService.update(question);
        }
        return ResponseEntity.ok(null);
    }

    public ResponseEntity setNotification(Notification notificationParam) {
        //1.获取用户id
        Long userId = UserHolder.get().getId();

        //2.通过用户id获取推送通知
        Notification notification = notificationService.findByUserId(userId);

        //3.判断对象是否为null
        if (notification == null) {
            //3.1若为空,保存
            notificationParam.setUserId(userId);

            notificationService.save(notificationParam);
        }else {
            //3.2 否则,更新
            notificationParam.setId(notification.getId());

            notificationService.update(notificationParam);
        }
        return ResponseEntity.ok(null);
    }

    public ResponseEntity findBlackListByPage(int pageNum, int pageSize) {
        //1.获取当前用户的id
        Long userId = UserHolder.get().getId();

        //2.调用service查询当前页的数据 Page
        Page<UserInfo> page = blackListService.findByPage(pageNum, pageSize, userId);

        //3.创建PageBeanVo对象
        //4.将 page对象中的数据设置到vo对象中
        PageBeanVo pageBeanVo = new PageBeanVo(page);

        //5.返回vo对象
        return ResponseEntity.ok(pageBeanVo);
    }

    public ResponseEntity deleteBlackList(Long blackId) {
        //1.获取当前用户id
        Long userId = UserHolder.get().getId();

        //2.调用service删除当前用户的一个黑名单
        blackListService.deleteByUserIdAndBlackId(userId,blackId);

        return ResponseEntity.ok(null);
    }

    public ResponseEntity sendCode(String phone) {
        String code = "123456";
        redisTemplate.opsForValue().set(ConstantUtil.SMS_CODE+phone+1,code, Duration.ofMinutes(5));
        return ResponseEntity.ok(null);
    }

    public ResponseEntity verifyCode(String phone, String requestCode) {
        //1.校验验证码是否正确
        String redisCode = redisTemplate.opsForValue().get(ConstantUtil.SMS_CODE + phone+1);

        //2.若错误,返回错误信息
        boolean verification;
        Map<String,Boolean> map = new HashMap<>();
        if (!StrUtil.equals(redisCode,requestCode)) {
            verification = false;
            return ResponseEntity.status(500).body(ErrorResult.loginError());
        }else {
            //3.若正确,删除验证码
            redisTemplate.delete(ConstantUtil.SMS_CODE + phone+1);
            verification = true;
            map.put("verification",verification);
        }
            return ResponseEntity.ok(map);
    }

    public ResponseEntity updatePhone(String phone) {

        //TODO 手机号二次修改
//判断手机号是否符合正则表达式
        Pattern pattern = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$");
        if (!pattern.matcher(phone).find()) {
            System.out.println(pattern.matcher(phone).find());
            return ResponseEntity.status(500).body("手机号格式不正确!");
        }
//判断该手机号用户是否存在
        User user1 = userService.findByPhone(phone);
        if (user1 != null) {
            return ResponseEntity.status(500).body("手机号已存在");
            //return ResponseEntity.status(500).body(ErrorResult.mobileError());
        } else {
            Long userId = UserHolder.get().getId();
            User user = new User();
            user.setPhone(phone);
            user.setId(userId);
            userService.update(user);
            return ResponseEntity.ok(null);
        }
    }

}
